package com.lysj.bhp.manager.controller;


import com.lysj.bhp.manager.base.ManagerContent;
import com.lysj.bhp.manager.domain.Privilege;
import com.lysj.bhp.util.web.ParamUtil;
import com.lysj.bhp.util.web.Resp;
import com.lysj.bhp.util.web.SelectItem;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("admin/privilege")
public class PrivilegeController extends ManagerContent {

    @GetMapping("list")
    public Resp list() {
        return new Resp(privilegeRepository.findAll(new Sort(Sort.Direction.ASC, "privilegeId")));
    }

    @PostMapping("add")
    public Resp add(Privilege model) {
        if (ParamUtil.isBlack(model.getName())) {
            return new Resp(Resp.PARAM_ERROR, "权限名称不能为空");
        }
        if (ParamUtil.isBlack(model.getUrl())) {
            return new Resp(Resp.PARAM_ERROR, "URL不能为空");
        }
        if (ParamUtil.isBlack(model.getParentId())) {
            model.setParentId(null);
            model.setIcon("&#xe610;");
        }
        if (!ParamUtil.isBlack(model.getParentId())) {
            model.setIcon("&#xe602;");
        }
        privilegeRepository.save(model);
        return new Resp("添加成功");
    }

    @PostMapping("edit")
    public Resp edit(Privilege model) {

        if (ParamUtil.isBlack(model.getPrivilegeId())) {
            return new Resp(Resp.PARAM_ERROR, "请选择权限");
        }
        Privilege privilege = privilegeRepository.findOne(model.getPrivilegeId());
        if (privilege == null) {
            return new Resp(Resp.PARAM_ERROR, "请选择权限");
        }
        if (ParamUtil.isBlack(model.getName())) {
            return new Resp(Resp.PARAM_ERROR, "权限名称不能为空");
        }
        if (ParamUtil.isBlack(model.getUrl())) {
            return new Resp(Resp.PARAM_ERROR, "URL不能为空");
        }
        if (ParamUtil.isBlack(model.getParentId())) {
            model.setParentId(null);
            model.setIcon("&#xe610;");
        }
        if (!ParamUtil.isBlack(model.getParentId())) {
            model.setIcon("&#xe602;");
        }
        privilegeRepository.save(model);
        return new Resp("修改成功");
    }

    @PostMapping("remove")
    public Resp remove(Privilege model) {
        privilegeRepository.delete(model.getPrivilegeId());
        return new Resp("删除成功");
    }

    @GetMapping("selectItem")
    public Resp findParentPrivilege() {
        List<SelectItem> selectItems = privilegeRepository.selectItems();
        return new Resp(selectItems);
    }
}
